const request = require('request');
const wallpaper = require('wallpaper');
const fs = require('fs');
const crypto = require('crypto');
const url = require('url');

class Wallpaper {
    /**
     *
     * @param imgUrl
     * @param savePath
     * @param option
     * @param callback<receivedBytes, totalBytes, localPath>
     * @returns {Promise<unknown>}
     */
    download(imgUrl, savePath, option = {}, callback) {
        return new Promise(function(reslove, reject) {
            let headers = getRequestHeaders(option);
            let req = request({
                url: imgUrl,
                method: "GET",
                headers: headers,
            });

            let totalBytes = 0;
            let receivedBytes = 0;
            let localPath = getImageFilePath(imgUrl, savePath);
            let imageFile = fs.createWriteStream(localPath);
            req.pipe(imageFile);
            req.on('response', (data) => {
                totalBytes = parseInt(data.headers['content-length'], 10);
            });
            req.on('data', (chunk) => {
                receivedBytes += chunk.length;
                if (typeof(callback) == 'function') {
                    callback(receivedBytes, totalBytes, localPath);
                }
            });
            req.on('end', function(){
                imageFile.end();
                reslove({'localPath' : localPath});
            });
            req.on('error', function(err) {
                reject(err)
            });
        });

    }

    /**
     *
     * @param localImagePath
     * @returns {Promise<void>}
     */
    async setWallpaper(localImagePath) {
        return await wallpaper.set(localImagePath);
    }
}
module.exports = Wallpaper;

function getUrlPathMd5(urlPath) {
    var parse = url.parse(urlPath);
    return crypto.createHash('md5').update(parse.pathname).digest('hex');
}

function getImageFilePath(urlPath, savePath) {
    savePath = savePath.replace(/([\s/\\]*$)/ig,"");
    let imageName = getUrlPathMd5(urlPath);
    return `${savePath}/${imageName}.jpg`;
}

function getRequestHeaders(option) {
    let headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7',
        'Cache-Control': 'max-age=0',
        'Connection': 'keep-alive',
        'Referer': option['referer'] ,
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
    };
    if (option['referer']) {
        headers['Referer'] = option['referer']
    }
    return headers;
}
